import CryptoJS from 'crypto-js'

const key = CryptoJS.enc.Utf8.parse('1234123412ABCDEF')     // 十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412')      // 十六位十六进制数作为密钥偏移量

// 解密方法
function Decrypt(word) {
    const encryptedHexStr = CryptoJS.enc.Hex.parse(word)
    const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
    const decrypt = CryptoJS.AES.decrypt(srcs, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
    })
    const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
    return decryptedStr.toString()
}
 
// 加密方法
function commEncrypt(word) {
    const srcs = CryptoJS.enc.Utf8.parse(word)
    const encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
    })
    return encrypted.ciphertext.toString().toUpperCase()
}

function encrypt(pwd, random) {
    const stage1Hash = CryptoJS.SHA1(pwd)
    const stage2Hash = CryptoJS.SHA1(stage1Hash)
    const scramble = CryptoJS.enc.Latin1.parse(random)
    const concated = scramble.concat(stage2Hash)
    const b = CryptoJS.SHA1(concated)
    const token = xor(stage1Hash, b)
    const back = xor(token, b) // xor back test
    console.log('back=>', back.toString())
    return token.toString()
}

function xor(wordArray1, wordArray2) {
    const arr = []
    for (let i = 0; i < wordArray1.sigBytes / 4; i++) {
        const r = wordArray1.words[i] ^ wordArray2.words[i]
        arr.push(r)
    }
    return CryptoJS.lib.WordArray.create(arr)
}

// 加密用户密码
export function encryptPwd(pwd, random) {
    return encrypt(pwd, random)
}
// 加密文字
export function textEncrypt(word) {
    return commEncrypt(word)
}
// 解密文字
export function textDecrypt(word) {
    return Decrypt(word)
}
